package com.gper.edu.vip.builder.prototype;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import lombok.Data;

import java.io.*;
import java.util.List;

/**
 * @Author: ellis.guan
 * @Description:
 * @Date: 2020/2/29 20:35
 * @Version: 1.0
 */
@Data
public class DeepClonePrototype implements Cloneable , Serializable {
    private String name;
    private int age;
    private List<String> hobbies;

    public DeepClonePrototype(String name, int age, List<String> hobbies) {
        this.name = name;
        this.age = age;
        this.hobbies = hobbies;
    }

    @Override
    public DeepClonePrototype clone() throws CloneNotSupportedException {
        ByteOutputStream bos = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try{
            bos = new ByteOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ois = new ObjectInputStream(new ByteArrayInputStream(bos.getBytes()));
            return (DeepClonePrototype) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (bos != null){
                bos.close();
            }
            if (oos != null){
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (ois != null){
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public List<String> getHobbies() {
        return hobbies;
    }
}
